package com.gp.billsrecord.ui.main.fragments

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.bottomsheets.BottomSheet
import com.afollestad.materialdialogs.list.listItemsMultiChoice
import com.gp.billsrecord.base.BaseFragment
import com.gp.billsrecord.databinding.FragmentMainBillFlowBinding
import com.gp.billsrecord.model.data.ConsumptionType
import com.gp.billsrecord.ui.main.adapters.BillFlowAdapter
import com.gp.billsrecord.util.DateUtil
import com.gp.billsrecord.vm.AppViewModel
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicLong

/*流水*/
class BillFlowFragment : BaseFragment<FragmentMainBillFlowBinding>() {
    private val viewModel by viewModels<AppViewModel>()
    private val filterAdapter = BillFlowAdapter()
    private val timeMs = AtomicLong()
    private val consumeTypes = arrayListOf<ConsumptionType>()
    private val consumeSelectList = arrayListOf<Int>()
    override fun onBindingCreated() {
        binding.tvFlowDate.setOnClickListener {
            //日期选择
            dateSelect()
        }
        binding.tvFlowFilter.setOnClickListener {
            //条件筛选
            filterSelect()
        }
        binding.rvBillFlows.also { recyclerView ->
            recyclerView.adapter = filterAdapter
            recyclerView.layoutManager = LinearLayoutManager(requireContext())
        }
    }

    private fun filterSelect() {
        val itms = consumeTypes.map { it.typeName }
        val index = consumeSelectList.toIntArray()
        //筛选条件
        MaterialDialog(requireContext(), BottomSheet()).show {
            listItemsMultiChoice(
                items = itms,
                initialSelection = index,
                waitForPositiveButton = true,
                allowEmptySelection = true
            ) { _, indices, _ ->
                consumeSelectList.clear()
                consumeSelectList.addAll(indices.toList())
                doFilter()
            }
            positiveButton {}
        }
    }

    private fun dateSelect() {
        //日期选择
        CardDatePickerDialog.builder(requireContext())
            .setTitle("日期选择")
            .setOnChoose {
                //日期选中
                timeMs.set(it)
                binding.tvFlowDate.text = DateUtil.formatDateTime(it, "YYYY年MM月")
                doFilter()
            }
            .setWrapSelectorWheel(false)
            .setMaxTime(System.currentTimeMillis())
            .setDisplayType(DateTimeConfig.YEAR, DateTimeConfig.MONTH)
            .showFocusDateInfo(false)
            .showBackNow(false)
            .build()
            .show()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        //监听并获取消费类型数据
        viewModel.observeConsumptionTypes().observe(viewLifecycleOwner) {
            consumeTypes.clear()
            consumeTypes.addAll(it)
        }
        //设置默认值
        timeMs.set(System.currentTimeMillis())
        binding.tvFlowDate.text = DateUtil.formatDateTime(timeMs.get(), "YYYY年MM月")
        doFilter()
    }

    private fun doFilter() {
        //把选中的消费类型集合转为id的集合
        val types = consumeSelectList.map { consumeTypes[it].typeId }
        viewLifecycleOwner.lifecycleScope.launch {
            viewModel.doBillFlowFilter(timeMs.get(), types).collectLatest(filterAdapter::submitData)
        }
    }
}